IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('MD3.RepopulateFKConstraints'))
BEGIN
	DROP PROCEDURE MD3.RepopulateFKConstraints
END
GO

CREATE Procedure MD3.RepopulateFKConstraints

AS  
BEGIN

/*
	Blows away all entries in MD3.FKConstraints table, EXCEPT entries with DropFK = 1.  We need to maintain this "state"
	Repopulates the table with current constraint information from the current database


*/

SET NOCOUNT ON  

	DELETE FROM MD3.FKConstraints WHERE DropFK = 0
	

    SET NOCOUNT ON  
	INSERT INTO MD3.FKConstraints
		(
			ForeignKeyName	,	
			SchemaName		,	
			TableName		,	
			KeyColumns		,	
			ParentSchemaName	,
			ParentTableName		,
			ParentKeyColumns	,
			IsNotTrusted       , 
			IsDeleteCascade    , 
			IsUpdateCascade    , 
			DropFK				
		)
	SELECT 
		Const.ForeignKeyName	,	
		Const.SchemaName		,	
		Const.TableName			,
		Const.KeyColumns		,	
		Const.ParentSchemaName	,
		Const.ParentTableName	,	
		Const.ParentKeyColumns	,
		Const.IsNotTrusted       , 
		Const.IsDeleteCascade     ,
		Const.IsUpdateCascade     ,
		0			
	FROM sys.objects AS o
	JOIN sys.schemas AS s 
		ON o.schema_id = s.schema_id
	CROSS APPLY MD3.f_GetForeignKeys(s.Name, o.Name) as Const
	WHERE o.type = 'U'
	AND s.name <> 'MD3'
	ORDER BY 
		SCHEMA_NAME(o.schema_id),
		o.Name


	
END
GO
